package com.project.common;

import com.project.dao.UserMapper;
import com.project.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CookieInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCacheManager redisCache;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if(uri.contains("login")){
            return true;
        }
        //校验cookie存的token
        String token = null;
        Cookie[] cookies = request.getCookies();
        A:for (Cookie cookie : cookies) {
            switch (cookie.getName()) {
                case "userToken":
                    token = cookie.getValue();
                    break A;
                default:
                    break;
            }
        }


        try {
            if(token != null){
                User user = redisCache.getUserByToken(token);
                if(user!=null && user.getId() != null){
                    User user2 = userMapper.selectByUserName(user.getUsername());
                    user2.setRole(user.getRole());
                    user2.setToken(user.getToken());
                    if(user2!=null){
                        redisCache.cacheUserInfo(user2);
                        request.setAttribute("userInfo_inter",user2);
                        return true;
                    }else{
                        request.setAttribute("userInfo_inter",null);
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            log.error("CookieInterceptor:50 用户Token获取失败", e);
            e.printStackTrace();
        }

        response.sendRedirect("/fw/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
